import {BaseInput} from './BaseInput';
import {AjaxMsg} from '../utils/AjaxMsg';

export class SmsVerifyCodeInput extends BaseInput {
    constructor(form, dom){
        super(form, dom);

        this._label = '短信验证码';

        this.dom.on('input', this.onInput.bind(this));
    }

    validate(){
        if(super.validate()){
            if (!(/^\d{6}$/.test(this.dom.val()))){
                this.setValidation(false, '验证码格式错误');
                return false;
            } else {
                return true;
            }
        } else {
            return false;
        }
    }

    onInput(){
        if(this.dom.val().length == 6 && this.form.mobileNumInput.getValue().length > 10 && this.validate()){
            let code = parseInt(this.dom.val());
            this.api.validateSmsVerifyCode(this.form.getFormData()).then((msg) => {
                let ajaxMsg = new AjaxMsg(msg);
                ajaxMsg.showFocus(this.form);
                this.form.shouldUseCaptcha = !!ajaxMsg.data.shouldUseCaptcha;
            });
        }
    }

    clear(){
        this.dom.val('');
        this.unsetValidation();
    }
}